package com.mixsmart.web.plugins;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.mixsmart.commonweb.IWebConstant;
import com.mixsmart.commonweb.plugins.IPlugin;
import com.mixsmart.commonweb.utils.SpringContextUtils;
import com.mixsmart.core.bean.MixResponse;
import com.mixsmart.core.service.IResQueryService;
import com.mixsmart.utils.CollectionUtils;
import com.mixsmart.utils.StringUtils;
import com.mixsmart.web.plugins.bean.ZTreeData;
import com.mixsmart.web.plugins.ztree.AbsObj2zTree;

/**
 * ZTree插件实现类
 * @author lmq
 * @version 1.0
 * @since 1.0
 * 2015年11月6日
 */
@Component("ztree")
public class ZTreePlugin implements IPlugin {

	@Autowired
	private IResQueryService resQueryServ;

	@Autowired
	@Qualifier("defaultObj2zTree")
	private AbsObj2zTree zTreeServ;
	
	/**
	 * 提供给Spring自动创建实例；
	 * 非Spring请调用有参数构造方法
	 */
	public ZTreePlugin() {
		//zTreeServ = new DefaultObj2zTree();
	}
	
	/**
	 * 提供给手工调用的构造方法；可以指定转换类
	 * @param convertTree 转化类
	 */
	public ZTreePlugin(AbsObj2zTree convertTree) {
		this.zTreeServ = convertTree;
		resQueryServ = SpringContextUtils.find(IResQueryService.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <E> MixResponse<E> getDatas(String resName, HashMap<String, Object> params) {
		MixResponse<E> mixResp = new MixResponse<E>();
		try {
			List<ZTreeData> lists = null;
			if(StringUtils.isNotEmpty(resName)) {
				Object async = params.get("isAsync");
				params.remove("isAsync");
				Boolean isAsync = false;
				if(null != async) {
					try {
						isAsync = Boolean.parseBoolean(async.toString());
					} catch (Exception e) {
						isAsync = false;
					}
				}
				MixResponse<Object> resp = resQueryServ.getDatas(resName, params);
				if(IWebConstant.OP_SUCCESS.equals(resp.getResult())) {
					List<Object> objs = resp.getDatas();
					try {
						if(CollectionUtils.isNotEmpty(objs)) {
							lists = zTreeServ.convert(objs,isAsync);
							if(CollectionUtils.isNotEmpty(lists)) {
								mixResp.setResult(IWebConstant.OP_SUCCESS);
								mixResp.setMsg(IWebConstant.OP_SUCCESS_MSG);
								mixResp.setDatas((List<E>)lists);
							}
							lists = null;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					objs = null;
				} 
				resp = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mixResp;
	}

	@Override
	public <E> MixResponse<E> getDatasPage(String resName,
			HashMap<String, Object> params, int page, int rows) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
